use reqwest::{self, Url};
use bytes::{self, Bytes};
use anyhow::{Result, anyhow, Error};
use tracing::{debug, error};

pub async fn http_get(url: &str) -> Result<Bytes, Error> {
    debug!("http get: {}", url);
    let client = reqwest::Client::new();

    let res = client.get(url)
    .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36 Edg/133.0.0.0")
    .send().await?;

    if !res.status().is_success() {
        return Err(anyhow!("download file failed: {}", res.status()));
    }

    res.bytes().await.map_err(|e| anyhow!("download file failed: {}", e).into())
}

pub async fn http_put(url: &str, data: Bytes) -> Result<(), Error> {
    debug!("http put: {}", url);
    let client = reqwest::Client::new();

    let res = client.put(url)
    .header("Content-Type", "application/octet-stream")
    .body(data)
    .send().await?;

    let status = res.status();
    if !status.is_success() {
        let body = res.text().await?;
        error!("upload file failed: {}", body);
        return Err(anyhow!("upload file failed: {}", status));
    }

    Ok(())
}